// pages/task_detl/components/taskOpr/taskOpr.js
import { mapKey } from '../../../../utils/config'
import { imgCompress } from "../../../../utils/img";

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    flag: {
      type: Boolean,
      value: false,
    },
    detl: {
      type: Object,
      value: {},
    },
    tabActive: {
      type: Number,
      value: 1
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    initProp: {},
    show: false,
    dateVal: wx.$util.formatDate(new Date(), 'yyyy-MM-dd HH:mm'),
    dateFlag: false,
    dateReset: false,
    kaishilichengshu: '',
    kaishilichengbiaozhao: '',
    jieshulichengshu: '',
    jieshulichengbiaozhao: '',
    useCarKm: '',
    lichengbiao: '',
    lichengbiaoFile: null,
    ranyoubiao: '',
    ranyoubiaoFile: null,

    watermark: [{
      content: '$time$',
      font: '34px sans-serif',
      lineWidth: 3,
      position: {
        bottom: 15,
        left: 15
      }
    },
    {
      content: '$location$',
      font: '28px sans-serif',
      lineWidth: 3,
      position: {
        bottom: 60,
        left: 15
      }
    },]
  },

  // 监听
  observers: {
    flag (val) {
      console.log(val, '查看数据呢')
      this.setData({
        lichengbiao: '',
        lichengbiaoFile: null,
      })
    },
  },
  onLoad () {
    console.log(this.data, '查看数据呢')
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onInput (e) { },

    onBlur (e) {
      let { value, } = e.detail,
        { key, } = e.currentTarget.dataset,
        reg = /^[1-9]?[0-9]{1,}\.{0,1}[0-9]*$/
      if (!value.length) return
      value = reg.test(value) ? Number(value) : ''
      this.setData({
        [key]: value,
      })

      if (key === 'endKM') {
        let start = this.data.detl.odometer_start_values || 0
        this.setData({
          useCarKm: value === '' ? '' : (value - start),
        })
      }
    },

    onClose (e) {
      this.triggerEvent('close')
    },
    onToggleDate (e) {
      this.setData({
        dateFlag: !this.data.dateFlag,
      })
    },
    onDateSelect (e) {
      let { detail, } = e
      this.setData({
        dateVal: detail,
      })
    },
    onChooseImg (e) {
      let { key, } = e.currentTarget.dataset
      wx.showLoading();
      this.getWatermarkData().then(opts => {
        wx.hideLoading();
        wx.chooseMedia({
          count: 1,
          mediaType: ['image'],
          // sourceType: ['album', 'camera'],
          sourceType: ['camera'],
          // sizeType: ['original', 'compressed'],  // 'original' 原图，原图文件太大传不动。
          sizeType: ['compressed'],
          success: async (res) => {
            let imgFile = res.tempFiles[0]
            // this.getWatermarkData().then(async opts => {
            await imgCompress(imgFile, opts, this).then(res => {
              console.log(res.tempFilePath, '添加水印');
              this.setData({
                [key]: res.tempFilePath,
                [`${key}File`]: res,
              })
            })
            // })
            // this.setData({
            //   [key]: imgFile.tempFilePath,
            //   [`${key}File`]: imgFile,
            // })
          },
        })

      })
      // wx.chooseMedia({
      //   count: 1,
      //   mediaType: ['image'],
      //   // sourceType: ['album', 'camera'],
      //   sourceType: ['camera'],
      //   // sizeType: ['original', 'compressed'],  // 'original' 原图，原图文件太大传不动。
      //   sizeType: ['compressed'],
      //   success: (res) => {
      //     let imgFile = res.tempFiles[0]
      //     this.getWatermarkData().then(async opts => {
      //       await imgCompress(imgFile, opts, this).then(res => {
      //         console.log(res.tempFilePath, '添加水印');
      //         this.setData({
      //           [key]: res.tempFilePath,
      //           [`${key}File`]: res,
      //         })
      //       })
      //     })
      //     this.setData({
      //       [key]: imgFile.tempFilePath,
      //       [`${key}File`]: imgFile,
      //     })
      //   },
      // })
    },
    onDelImg (e) {
      let { key, } = e.currentTarget.dataset
      wx.showModal({
        title: '确认删除该图片？',
        success: res => {
          if (res.confirm) {
            this.setData({
              [key]: '',
              [`${key}File`]: null,
            })
          }
        },
      })
    },

    // 接口
    async onStart (e) {
      // let { detl, dateVal, lichengbiao, lichengbiaoFile, ranyoubiao, ranyoubiaoFile, startKM, startL, } = this.data,
      //   { order_id, dispatch_id, } = detl,
      //   post = {
      //     order_id,
      //     dispatch_id,
      //     dispatch_status_id: '',
      //     dispatch_status_name: '',
      //     odometer_start_values: startKM,
      //     fuel_start_values: startL,
      //     send_car_time: dateVal,
      //     remark: '',
      //   }

      /* if([startKM, startL].includes('')) {
        wx.$toast('请填写开始里程表和开始燃油表')
        return
      } */
      // if ([startKM].includes('')) {
      //   wx.$toast('请填写开始里程表')
      //   return
      // }
      // if(!lichengbiaoFile || !ranyoubiaoFile) {
      //   wx.$toast('请按要求上传图片！')
      //   return
      // }
      /* if((lichengbiaoFile && !ranyoubiaoFile) || (!lichengbiaoFile && ranyoubiaoFile)) {
        wx.$toast('图片必须上传两张或不传！')
        return
      }

      wx.showLoading()
      let uploadImgObj = lichengbiaoFile && ranyoubiaoFile ? await this.getUploadImgSrc() : {}
      post = {
        ...post,
        fuel_images: [],
        odometer_images: [],
        ...uploadImgObj,
      } */

      // wx.showLoading()
      // let uploadImgObj = await this.getUploadImgSrc()
      // post = {
      //   ...post,
      //   fuel_images: [],
      //   odometer_images: [],
      //   ...uploadImgObj,
      // }

      // wx.$post('/dri/sell/order/update/dispatch/vehicle/start', post).then(res => {
      //   if (res.code !== 10000) return
      //   wx.$toast('提交成功！').then(() => {
      //     this.onClose()
      //     this.triggerEvent('success')
      //     this.resetUpload()
      //   })
      // })

      if (this.data.tabActive == 1) {
        if (!this.data.kaishilichengshu) return wx.$toast("请填写开始里程表")
      } else {
        if (!this.data.jieshulichengshu) return wx.$toast("请填写结束里程表")
      }
      if (!this.data.lichengbiao) return wx.$toast("请拍照上传里程表的图片")
      let { lichengbiao, kaishilichengshu, jieshulichengshu, lichengbiaoFile } = this.data;
      let row_id = this.data.detl.row_id
      let postData = {
        kaishilichengshu,
        lichengbiao,
        jieshulichengshu,
        row_id
      }
      // let uploadImgObj = await this.getUploadImgSrc()
      // 上传图片
      let uploadImgObj = await this.uploadImg(lichengbiaoFile)
      if (uploadImgObj.response.errcode != 0) return wx.$toast(uploadImgObj.response.errmsg);
      if (uploadImgObj.data.row && uploadImgObj.data.row.length > 0) {
        postData.lichengbiao = uploadImgObj.data.row[0].data
      } else {
        return wx.$toast("上传图片失败,请重新上传")
      }
      this.resetUpload()
      this.triggerEvent('success', postData)
    },
    // async onComplete(e) {
    //   let { detl, dateVal, useCarKm, lichengbiao, lichengbiaoFile, ranyoubiao, ranyoubiaoFile, endKM, endL, } = this.data,
    //     { order_id, dispatch_id, send_car_time, odometer_start_values, fuel_start_values, } = detl,
    //     post = {
    //       order_id,
    //       dispatch_id,
    //       dispatch_status_id: '',
    //       dispatch_status_name: '',
    //       send_car_time,
    //       return_car_time: dateVal,
    //       odometer_start_values,
    //       odometer_end_values: endKM,
    //       use_car_kilometers: useCarKm,
    //       fuel_start_values,
    //       fuel_end_values: endL,
    //       fuel_total_rise: fuel_start_values - endL,
    //       dispatch_car_order_amount: '',
    //       is_finish: true,
    //       remark: '',
    //     }

    //   /* if([endKM, endL].includes('')) {
    //     wx.$toast('请填写结束里程表和结束燃油表')
    //     return
    //   } */
    //   if ([endKM].includes('')) {
    //     wx.$toast('请填写结束里程表')
    //     return
    //   }
    //   // if(!lichengbiaoFile || !ranyoubiaoFile) {
    //   //   wx.$toast('请按要求上传图片！')
    //   //   return
    //   // }
    //   /* if((lichengbiaoFile && !ranyoubiaoFile) || (!lichengbiaoFile && ranyoubiaoFile)) {
    //     wx.$toast('图片必须上传两张或不传！')
    //     return
    //   }

    //   wx.showLoading()
    //   let uploadImgObj = lichengbiaoFile && ranyoubiaoFile ? await this.getUploadImgSrc() : {}
    //   post = {
    //     ...post,
    //     fuel_images: [],
    //     odometer_images: [],
    //     ...uploadImgObj,
    //   } */

    //   wx.showLoading()
    //   let uploadImgObj = await this.getUploadImgSrc()
    //   post = {
    //     ...post,
    //     fuel_images: [],
    //     odometer_images: [],
    //     ...uploadImgObj,
    //   }

    //   wx.$post('/dri/sell/order/update/dispatch/vehicle/finish', post).then(res => {
    //     if (res.code !== 10000) return
    //     wx.$toast('提交成功！').then(() => {
    //       this.onClose()
    //       this.triggerEvent('success')
    //       this.resetUpload()
    //     })
    //   })
    // },
    getUploadImgSrc () {
      let { lichengbiaoFile } = this.data,
        proArr = [this.uploadImg(lichengbiaoFile)]
      return new Promise((resolve, reject) => {
        Promise.all(proArr).then(res => {
          let obj = {}
          res.forEach((item, i) => {
            let key = i ? 'fuel_images' : 'odometer_images'
            obj[key] = item ? [{
              name: '',
              img_src: item,
              description: '',
              remark: '',
              state: '',
            }] : []
          })
          resolve(obj)
        })
      })
    },
    uploadImg (file) {
      return new Promise((resolve, reject) => {
        if (!file) {
          resolve('')
          return
        }
        wx.$uploadReq(file.tempFilePath).then(res => {
          resolve(res)
        })
      })
    },
    resetUpload () {
      this.setData({
        lichengbiao: '',
        lichengbiaoFile: null,
        ranyoubiaoFile: null,
      })
    },


    //  240309 yan 修改上传图片添加水印，
    /**
     * 获取水印信息
     * */
    getWatermarkData () {
      let detl = this.data.detl,
        mark = [
          {
            content: '$time$',
            font: '34px sans-serif',
            lineWidth: 3,
            position: {
              bottom: 15,
              left: 15
            }
          },
          {
            content: '$location$',
            font: '28px sans-serif',
            lineWidth: 3,
            position: {
              bottom: 60,
              left: 15
            }
          },
          {
            content: detl.siji1xingming,
            font: '36px sans-serif',
            lineWidth: 3,
            position: {
              bottom: 100,
              left: 15
            }
          },
          {
            content: detl.chepaihaoma,
            font: '36px sans-serif',
            lineWidth: 3,
            position: {
              bottom: 140,
              left: 15
            }
          },
        ];
      return new Promise(async (resolve, reject) => {
        let opts = [];
        for (let i = 0; i < mark?.length; i++) {
          let item = { ...mark[i] };
          //定位
          if (item.content === '$location$') {
            wx.showLoading({ mask: true });
            await this.wxLocation().then(res => {
              wx.hideLoading();
              let { address, location, formatted_addresses } = res.result;
              address = formatted_addresses && formatted_addresses.recommend || address;
              item.content = address;
            }).catch(() => {
              wx.hideLoading();
              reject()
            })
          }
          if (item.content === '$time$') {
            item.content = wx.$util.formatDate(new Date(), 'yyyy-MM-dd HH:mm');
          }
          opts.push(item);
        }
        resolve(opts);
      })
    },
    //  获取当前位置
    wxLocation () {
      return new Promise((resolve, reject) => {
        wx.$getLocation().then(res => {
          this.mapGeocoder(res).then(result => {
            resolve(result);
          })
        }, reject)
      })
    },

    //腾讯地图api逆地址转换
    mapGeocoder (latlng) {
      let { latitude, longitude } = latlng;
      return new Promise(resolve => {
        wx.$post(2, 'map/tencent/ws/geocoder/location', {
          "key": mapKey,
          "location": `${latitude},${longitude}`,
          "get_poi": "",
          "poi_options": "",
          "output": "",
          "callback": ""
        }, false, true).then(res => {
          resolve(res)
        })
      })
    },
    showProImg () {
      wx.previewImage({
        urls: [this.data.lichengbiao]
      })
    }

  },
})
